package leecode

func averageOfLevels(root *TreeNode) (avg []float64) {
	if root == nil {
		return
	}
	dqueue := []*TreeNode{root}
	for len(dqueue) != 0 {
		size := len(dqueue)
		temp := make([]int, 0)
		for i := 0; i < size; i++ {
			temp = append(temp, dqueue[i].Val)
			if dqueue[i].Left != nil {
				dqueue = append(dqueue, dqueue[i].Left)
			}
			if dqueue[i].Right != nil {
				dqueue = append(dqueue, dqueue[i].Right)
			}
		}
		dqueue = dqueue[size:]
		sum := 0
		for _, value := range temp {
			sum += value
		}
		avgNum := float64(sum) / float64(len(temp))
		avg = append(avg, avgNum)
	}
	return
}
